package org.jasig.cas.web.flow;

import javax.validation.constraints.NotNull;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.webflow.execution.RequestContext;

import com.callbell.cas.context.CaptchaConst;
import com.callbell.cas.context.CaptchaContext;
import com.google.code.kaptcha.Constants;

/**
 * Generates the login ticket parameter as described in section 3.5 of the <a
 * href="http://www.jasig.org/cas/protocol">CAS protocol</a>.
 *
 * @author Marvin S. Addison
 * @version $Revision$ $Date$
 * @since 3.4.9
 *
 */
public class GenerateLoginTicketAction {
	/** 3.5.1 - Login tickets SHOULD begin with characters "LT-" */
	private static final String PREFIX = "LT";

	/** Logger instance */
	private final Log logger = LogFactory.getLog(getClass());

	@NotNull
	private UniqueTicketIdGenerator ticketIdGenerator;

	public final String generate(final RequestContext context) {
		// 生成随机ticket
		final String loginTicket = this.ticketIdGenerator.getNewTicketId(PREFIX);
		this.logger.debug("Generated login ticket " + loginTicket);
		// 将ticket置入context.getFlowScpte中
		WebUtils.putLoginTicket(context, loginTicket);
		String capText = (String) context.getExternalContext().getSessionMap().get(Constants.KAPTCHA_SESSION_KEY);
		String loginName = (String) context.getExternalContext().getSessionMap().get("loginName");
		if (loginName != null && capText != null) {
			Integer attemptLoginCount = CaptchaContext.getAttemptLoginCount(loginName);
			if (attemptLoginCount != null) {
				context.getFlashScope().put("remainLoginCountForShow", CaptchaConst.MAX_ATTEMP_LOGIN_COUNT - attemptLoginCount);
			}
		}
		return "generated";
	}

	public void setTicketIdGenerator(final UniqueTicketIdGenerator generator) {
		this.ticketIdGenerator = generator;
	}

}
